package com.link.ppt.Utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.text.TextUtils;

import java.io.IOException;

/**
 * Created by liucxu on 2017/9/18.
 */

public class SimpleMediaPlayerUtils {

    private MediaPlayer player = null;
    private static Context context;
    private static SimpleMediaPlayerUtils instance = null;
    private VoicePlayInterface callback;
    private String voiceUrl = "";

    private SimpleMediaPlayerUtils() {
    }

    /**
     * 回调接口但是不支持进度的回调
     */
    public interface VoicePlayInterface {

        void onStartPlaying();

        void onPause();

        void onPlayCompleted();
    }

    /**
     * 单例化SimpleMediaPlayerUtils
     *
     * @param context
     * @return
     */
    public static SimpleMediaPlayerUtils getInstance(Context context) {
        if (instance == null) {
            SimpleMediaPlayerUtils.context = context;
            instance = new SimpleMediaPlayerUtils();
        }
        return instance;
    }

    public void play(String voice, VoicePlayInterface call) {
        player = player == null ? new MediaPlayer() : player;
        if (call == null) {
            ToastUtils.showShortToast(context, "请完善回调接口");
            return;
        }
        if (TextUtils.isEmpty(voice)) {
            ToastUtils.showShortToast(context, "音频地址不能为空");
            return;
        }
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                callback.onPlayCompleted();
            }
        });

        if (TextUtils.isEmpty(voiceUrl)) {
            callback = call;
            voiceUrl = voice;
            callback.onStartPlaying();
            try {
                player.setDataSource(voice);
                player.prepare();
                player.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (!voiceUrl.equals(voice)) {
                voiceUrl = voice;
                callback.onPlayCompleted();
                callback = call;
                callback.onStartPlaying();
                player.reset();
                try {
                    player.setDataSource(voice);
                    player.prepare();
                    player.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                if (player.isPlaying()) {
                    player.pause();
                    callback.onPause();
                } else {
                    callback.onStartPlaying();
                    player.start();
                }
            }
        }
    }

    public void releaseMediaPlayer(){
        if (player != null) {
            player.release();
            player = null;
        }
        callback=null;
        voiceUrl="";
    }
}
